// 2025/3/10
// https://leetcode.cn/problems/kth-smallest-element-in-a-bst/?envType=study-plan-v2&envId=top-100-liked
// 二叉搜索树中第k小的元素

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            stack<TreeNode*> st;
            while(root || !st.empty())
            {
                while(root)
                {
                    st.emplace(root);
                    root = root->left;
                }
                root = st.top();
                st.pop();
                k--;
                if(k == 0)
                    break;
                
                root = root->right;
            }
            return root->val;
        }
    };